package http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.Arrays;

/**
 * Created by Administrator on 2016/7/24.
 */
public class HexStringTest {

    static String  hexString = "ef020812340000000000000005000000c8000000c8ef02";
    public static void main(String[] args) throws Exception{
//        byte[] bytes = ByteAndHex.hexStringToBytes(hexString);
        System.out.println(hexString.length());
        System.out.println(ByteAndHex.hexStringToBytes(hexString).length);
        byte[] bbbbb = ByteAndHex.hexStringToBytes(hexString);
        byte[] bytes = subBytes(bbbbb, 13, 4);
//        byte[] bytes = intToByteArray(-33421);
//        int i = -33421;
//        ByteArrayOutputStream boutput = new ByteArrayOutputStream();
//        DataOutputStream doutput = new DataOutputStream(boutput);
//        doutput.writeInt(i);
//        byte[] bytes = boutput.toByteArray();
        System.out.println(ByteAndHex.bytesToHexString(bytes));

//        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
//        int result = in.read();

        int result = byteArrayToInt(bytes,0,4);
        System.out.println(result);

        byte[] byte2s = subBytes(bbbbb, 17, 4);
//        byte[] bytes = intToByteArray(-33421);
        System.out.println(ByteAndHex.bytesToHexString(byte2s));

        int result2 = byteArrayToInt(byte2s,0,4);
        System.out.println(result2);
    }

    public static int byteArrayToInt(byte[] b, int offset,int count) {
        int value = 0;
        for (int i = 0; i < count; i++) {
            int shift = (count - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }

    public static byte[] intToByteArray (final int integer) {
        int byteNum = (40 - Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer)) / 8;
        byte[] byteArray = new byte[4];

        for (int n = 0; n < byteNum; n++)
            byteArray[3 - n] = (byte) (integer >>> (n * 8));

        return (byteArray);
    }

    /**
     * 从一个byte[]数组中截取一部分
     * @param src
     * @param begin
     * @param count
     * @return
     */
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        for (int i=begin; i<begin+count; i++)
            bs[i-begin] = src[i];
        return bs;
    }
}
